import {userApi} from "@/core/request/api/UserApi";
import Vue from "vue";
import SafeUtils from "@/core/utils/SafeUtils";
import SparkMD5 from "spark-md5";

const user = {
  state: {
    uuid: '',
    token: '',
    name: '',
    roles: {
      admin: "管理员",
      user: "用户",
      dev:"开发者",
      ban: "封禁用户"
    },
    genders:['未知','男','女'],
    info: {},
    hexMsg:'',
  },

  mutations: {
    SET_UUID: (state, uuid) => {
      state.uuid = uuid
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, { name, welcome }) => {
      state.name = name
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_INFO: (state, info) => {
      state.info = info
    },
    SET_HEXMSG: (state, hexMsg) => {
      state.hexMsg = hexMsg
    }
  },

  actions: {
    // getUUID
    setToken({commit},token=null){

          commit('SET_TOKEN', token)


    },
    getUUIDputState({commit}) {
      return new Promise((resolve, reject) => {
        // 获取公钥
        userApi.getPbs().then(res =>{
          if (!res.data.code){
            var pbk = res.data.data
            // 生成传输私钥
              // 使用sparkmd5对公钥加上随机数在加密
            var secret = SparkMD5.hash(res.data.data+Math.random()).substr(0,16)
            // 使用公钥加密私钥
            var hexMsg = SafeUtils.RSAEncrypt(secret,pbk);
            // 发送请求
            userApi.getUUID({
              pub:pbk,
              hexMsg
            }).then(res=>{
              commit('SET_UUID', res.data.data)
              commit('SET_HEXMSG', secret)
              Vue.prototype.axios.defaults.headers.common['Uuid']=res.data.data
              resolve(res)
            })
          }
        }).catch(err => {
          reject(err)
        })
      })
    },
    //setInfo
    getINFOputState({commit}){
      return new Promise((resolve, reject) => {
        Vue.prototype.axios.get(userApi.getInfo).then(res => {
          commit('SET_INFO', res.data.data)
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    }
  },
  getters:{
    getInfo(state){
      return state.info
    },
  }
}

export default user
